import { loginApi, getInfoApi, loginOutApi } from "@/api/user";
import { ElMessage } from "element-plus";

const state = () => ({
  token: "", // 登录token
  info: {} // 用户信息
});

// getters
const getters = {
  token(state) {
    return state.token;
  }
};

// mutations
const mutations = {
  tokenChange(state, token) {
    state.token = token;
  },
  infoChange(state, info) {
    state.info = info;
  }
};

// actions
const actions = {
  // login by login.vue
  login({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      loginApi(params).then(res => {
        console.log(res);
        if (res.code == 0) {
          commit("tokenChange", res.data.api_token);
          // dispatch('getInfo', { token: res.data.api_token })  // 直接获取，去除这个接口
          // .then(infoRes => {
          commit("infoChange", res.data);
          resolve(res);

          // })
        } else {
          resolve(res);
          // ElMessage.error({
          //   message: res.message,
          //   type: "error",
          //   showClose: true
          // });
        }
      });
    });
  },
  // get user info after user logined
  getInfo({ commit }, params) {
    // 获取用户信息
    return new Promise((resolve, reject) => {
      getInfoApi(params).then(res => {
        commit("infoChange", res.data.info);
        resolve(res.data.info);
      });
    });
  },

  // login out the system after user click the loginOut button
  loginOut({ commit }) {
    loginOutApi()
      .then(res => {})
      .catch(error => {})
      .finally(() => {
        localStorage.removeItem("tabs");
        localStorage.removeItem("vuex");
        location.reload();
      });
  }
};

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
};
